/**
 *
 */
package com.angel.dao.generic.base;

import java.util.ArrayList;
import java.util.Collection;
import java.util.SortedSet;
import java.util.TreeSet;

import com.angel.dao.generic.comparators.FindAllInstancesFilterPriorityComparator;
import com.angel.dao.generic.interfaces.FindAllInstancesFilter;

/**
 *
 * @author William
 *
 */
public class InstancesFilterManager<T extends Object> {

	private SortedSet<FindAllInstancesFilter<T>> filters;

	public InstancesFilterManager(){
		super();
		this.filters = new TreeSet<FindAllInstancesFilter<T>>(new FindAllInstancesFilterPriorityComparator<T>());
	}

	public boolean addInstancesFilter(FindAllInstancesFilter<T> filter){
		return this.filters.add(filter);
	}

	public void clearFilters(){
		this.filters.clear();
	}

	public Collection<T> appliesFilters(Collection<T> instances){
		Collection<T> resultCollection = new ArrayList<T>();
		if(filters.size() > 0){
			for(FindAllInstancesFilter<T> filter: filters){
				for(T entity: instances){
					if(filter.appliesFilter(entity)){
						resultCollection.add(entity);
					}
				}
			}
		} else {
			resultCollection = instances;
		}
		return resultCollection;
	}
}
